package com.california.pay.socket.server;


import com.bwton.socket.util.EncodeUtil;
import com.bwton.socket.util.RemotingUtil;
import com.california.pay.socket.TransSocketMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 行业前置服务端解码器
 *
 * @author liangd.chen
 * @date 2018/8/20
 */
public class SocketServerDecoder extends ByteToMessageDecoder {
    private static final Logger logger = LoggerFactory.getLogger("TCP_NETTY_LOG");

    public SocketServerDecoder() {
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Object obj;
        try {
            obj = decode(ctx, in);
        } catch (Exception e) {
            logger.error("解析请求报文异常，丢弃该条消息！remote_uri=" + RemotingUtil.parseRemoteAddress(ctx.channel()), e);
            in.clear();
            throw e;
        }
        out.add(obj);
    }

    private Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        byte[] data = new byte[in.readableBytes()];
        in.readBytes(data);

        TransSocketMessage tms = new TransSocketMessage(true, data);
        tms.setRemoteIp(RemotingUtil.parseRemoteAddress(ctx.channel()));
        printSocketMessage(ctx, tms.getSocketBody());
        return tms;
    }

    private void printSocketMessage(ChannelHandlerContext ctx, String socketBody) {
        if (logger.isInfoEnabled()) {
            String line = EncodeUtil.getOsSeparator();
            StringBuilder tmp = new StringBuilder();
            tmp.append(line).append("#####收到报文(十六进制), remote_uri=" + RemotingUtil.parseRemoteAddress(ctx.channel())).append(line);
            tmp.append(socketBody).append(line);
            logger.info(tmp.toString());
        }
    }

}
